package utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzInitializer extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static Logger jLog = Logger.getLogger(QuartzInitializer.class);

	private Scheduler scheduler = null;

	public void init() throws ServletException {

		try {

			SchedulerFactory sf = new StdSchedulerFactory();
			scheduler = sf.getScheduler();

			JobDetail job = newJob(application.PictureJob.class).withIdentity(
					"PictureJob").build();

			CronTrigger trigger = newTrigger().withIdentity("PictureTrigger")
					.withSchedule(cronSchedule("0 0/10 * * * ?")).build();

//			CronTrigger trigger = newTrigger().withIdentity("PictureTrigger")
//					.withSchedule(cronSchedule("0/10 * * * * ?")).build();

			scheduler.scheduleJob(job, trigger);

			scheduler.start();
			
			jLog.info("Job erstellt und Scheduler gestartet");

		} catch (SchedulerException e) {
			jLog.info("Konnte Picture-Job nicht erstellen");
			e.printStackTrace();
		}

	}

	public void destroy() {
		try {
			// Note: passing true into the shutdown message tells the Quartz
			// Scheduler to wait until all jobs have completed running before
			// returning from the method call.
			scheduler.shutdown(true);
			jLog.info("Jobs beendet und Scheduler gestoppt");
		
		} catch (SchedulerException e) {
			jLog.info("Konnte Scheduler nicht stoppen");
			e.printStackTrace();
		}
	}

}
